var express = require('express');
var router = express.Router();
const pool = require('../settings/pool')
const remotePool = require('../settings/remote.pool')
const createJSON = require('../settings/api')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/get', function (req, res, next) {
  var query = pool.query('select * from user', function (err, rows, fields) {
    if (err) {
      throw err
      res.json(createJSON({
        data: [],
        success: false,
        msg: "数据问题"
      }))
    }
    res.json(createJSON({
      data: rows
    }))
  })
})

// get: req.query, get: req.body
router.get('/get/:id', function (req, res, next) {
  var id = req.params.id
  var query = pool.query('select * from user where id = ?', [id], function (err, rows, fields) {
    if (err) {
      throw err
      res.json(createJSON({
        data: [],
        success: false,
        msg: "数据问题"
      }))
    }
    res.json(createJSON({
      data: rows
    }))
  })
})

router.get('/remote', function(req, res, next) {
  var query = remotePool.query('select * from user', function (err, rows, fields) {
    if (err) {
      res.json(createJSON({
        data: [],
        success: false,
        msg: err
      }))
      throw err
    }
    res.json(createJSON({
      data: rows
    }))
  })
})

/*
// get: req.query, get: req.body
router.get('/insert', function (req, res, next) {
  connection.connect()
  var username = req.query.username
  var password = req.query.password
  var age = req.query.age
  //var sql = "insert into user('username', 'password', 'age') values ('" + username + "', '"+ password +"', " + age + ")"
  var sql = "insert into user (username, password, age) values ('Alax', '123', 4)";
  console.log(sql)
  var query = connection.query(sql, function (err, rows, fields) {
      if(err) throw err
      res.json({
        success: true,
        msg: "插入成功",
        data: req.query
      })
  })

  connection.end()
})
*/

module.exports = router;
